import { defineStore } from 'pinia'
import { store } from '../index'
import { parse, stringify } from 'zipson'
import { LanguageEnum, ThemeEnum } from '@renderer/enums/SettingEnum'
import { useI18n } from 'vue-i18n'
import { languageOptions } from '@renderer/language'

interface SettingsState {
  // 主题
  theme: ThemeEnum
  // 字体大小
  fontSize: number
  // 语言
  language: LanguageEnum
  // 保存路径
  outSavePath: string
  // 摄像头
  cameraId: string
  // 麦克风
  microphoneId: string
  // 可用摄像头列表
  cameraList: MediaDeviceInfo[]
  // 可用麦克风列表
  microphoneList: MediaDeviceInfo[]
}

export const useSettingsStore = defineStore('settingsStore', {
  state: (): SettingsState => ({
    theme: ThemeEnum.LIGHT,
    fontSize: 16,
    language: LanguageEnum.SIMPLE_ZH,
    outSavePath: '',
    cameraId: '',
    microphoneId: '',
    cameraList: [],
    microphoneList: []
  }),
  getters: {
    getNowLanguageLabel: (state) => {
      return languageOptions.find((item) => item.value === state.language)?.label || '简体中文'
    },
    getNowThemeLabel: (state) => {
      return 'theme.' + state.theme || 'Light'
    },
    getCameraList: (state) => {
      // 添加一个空字符串
      return [
        { id: '', label: '无' },
        ...state.cameraList.map((item) => ({
          id: item.deviceId,
          label: item.label
        }))
      ]
    },
    getMicrophoneList: (state) => {
      return [
        { id: '', label: '无' },
        ...state.microphoneList.map((item) => ({
          id: item.deviceId,
          label: item.label
        }))
      ]
    }
  },
  actions: {
    // 初始化设置
    init() {
      this.initLanguage()
      this.initTheme()
      this.getMediaDevices()
    },

    // 初始化语言
    initLanguage() {
      const { locale } = useI18n()
      if (!this.language) {
        this.language = LanguageEnum.SIMPLE_ZH
      }
      locale.value = this.language
    },

    // 切换语言
    switchLanguage(language: LanguageEnum) {
      this.language = language
    },

    // 获取系统中可用的摄像头和麦克风列表
    async getMediaDevices() {
      try {
        // 检查浏览器是否支持 MediaDevices API
        if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
          console.error('浏览器不支持 MediaDevices API')
          return
        }

        // 请求权限
        await navigator.mediaDevices
          .getUserMedia({ audio: true, video: true })
          .then((stream) => {
            // 获取权限后，立即释放流
            stream.getTracks().forEach((track) => track.stop())
          })
          .catch((err) => {
            console.warn('无法获取媒体设备权限:', err)
          })

        // 枚举所有媒体设备
        const devices = await navigator.mediaDevices.enumerateDevices()

        // 过滤出摄像头设备
        this.cameraList = devices.filter((device) => device.kind === 'videoinput')

        // 过滤出麦克风设备
        this.microphoneList = devices.filter((device) => device.kind === 'audioinput')

        console.log('可用摄像头:', this.cameraList)
        console.log('可用麦克风:', this.microphoneList)
      } catch (error) {
        console.error('获取媒体设备列表失败:', error)
      }
    },

    // 选择特定摄像头
    async selectCamera(deviceId: string) {
      try {
        if (this.cameraId) {
          // 停止当前摄像头
          const stream = await navigator.mediaDevices.getUserMedia({
            video: {
              deviceId: { exact: this.cameraId }
            }
          })
          stream.getTracks().forEach((track) => track.stop())
          this.cameraId = ''
        }

        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            deviceId: { exact: deviceId }
          }
        })

        const videoTrack = stream.getVideoTracks()[0]
        if (videoTrack) {
          this.cameraId = videoTrack.id
        }
        return videoTrack
      } catch (error) {
        console.error('选择摄像头失败:', error)
        return null
      }
    },

    // 选择特定麦克风
    async selectMicrophone(deviceId: string) {
      try {
        if (this.microphoneId) {
          // 停止当前麦克风
          const stream = await navigator.mediaDevices.getUserMedia({
            audio: {
              deviceId: { exact: this.microphoneId }
            }
          })
          stream.getTracks().forEach((track) => track.stop())
          this.microphoneId = ''
        }

        const stream = await navigator.mediaDevices.getUserMedia({
          audio: {
            deviceId: { exact: deviceId }
          }
        })
        const audioTrack = stream.getAudioTracks()[0]
        if (audioTrack) {
          this.microphoneId = audioTrack.id
        }
        return audioTrack
      } catch (error) {
        console.error('选择麦克风失败:', error)
        return null
      }
    },

    // 初始化主题
    initTheme() {
      if (!this.theme) {
        // 默认使用系统主题
        this.theme = ThemeEnum.SYSTEM
      }

      // 如果是系统主题，则根据系统偏好设置
      if (this.theme === ThemeEnum.SYSTEM) {
        const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
        document.documentElement.classList.toggle('dark', isDarkMode)
      } else {
        // 否则使用用户选择的主题
        document.documentElement.classList.toggle('dark', this.theme === ThemeEnum.DARK)
      }
    },

    // 切换主题（在亮色和暗色模式系统模式之间切换）
    toggleTheme() {
      if (this.theme === ThemeEnum.SYSTEM) {
        // 如果当前是系统主题，切换到明确的亮色/暗色模式
        const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
        this.theme = isDarkMode ? ThemeEnum.LIGHT : ThemeEnum.DARK
      } else if (this.theme === ThemeEnum.LIGHT) {
        // 从亮色模式切换到暗色模式
        this.theme = ThemeEnum.DARK
      } else if (this.theme === ThemeEnum.DARK) {
        // 从暗色模式切换到系统模式
        this.theme = ThemeEnum.SYSTEM
      }

      // 更新html元素的class
      if (this.theme === ThemeEnum.SYSTEM) {
        const systemIsDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        document.documentElement.classList.toggle('dark', systemIsDark)
      } else {
        document.documentElement.classList.toggle('dark', this.theme === ThemeEnum.DARK)
      }
    },

    // 设置指定主题
    setTheme(newTheme: ThemeEnum) {
      this.theme = newTheme

      if (newTheme === ThemeEnum.SYSTEM) {
        // 如果设置为系统主题，则根据系统设置
        const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
        document.documentElement.classList.toggle('dark', isDarkMode)
      } else {
        // 否则使用用户选择的主题
        document.documentElement.classList.toggle('dark', newTheme === ThemeEnum.DARK)
      }
    },

    // 根据系统主题更新当前主题
    updateThemeBySystem(systemTheme: ThemeEnum) {
      if (this.theme === ThemeEnum.SYSTEM) {
        document.documentElement.classList.toggle('dark', systemTheme === ThemeEnum.DARK)
      }
    },

    // 设置保存路径
    setOutSavePath(path: string) {
      this.outSavePath = path
    }
  },
  persist: {
    key: 'settings',
    storage: localStorage,
    serializer: {
      deserialize: parse,
      serialize: stringify
    }
  }
})

// 非setup
export function useSettingsStoreHook() {
  return useSettingsStore(store)
}
